﻿<?php

/*--------------------------------------------
Штрафи/Бали/Заработано
---------------------------------------------*/
	function ball(){
	$GLOBALS['h1']='Статистика по зарплате мастера за месяц';
	$money = '<div class="row-fluid"><div class="span6"><table class="table table-bordered"><thead><tr><th>Месяц</th><th>Бонусов (руб.)</th><th>Штрафов (руб.)</th><th>Заработано (руб.)</th></tr></thead><tbody>';
		
	//це все може потім зникнути
	$year = date('Y');
	$month_number = date('m');
	$mon = array('нолябрь','январь','февраль','март','апрель','май','июнь','июль','август','сентябрь','октябрь','ноябрь','декабрь');
	$month=$mon[(int)$month_number];
	
	$date_start_month = unix_date("1.".(int)$month_number.".".$year);
	$date_end_month = unix_date("1.".((int)$month_number+1).".".$year);
		
		$date = date('Y.m.d', $date_start_month);
		
		$query2 = "SELECT date_end_remont FROM orders";
		$res2=mysql_query($query2);
		$row2=mysql_fetch_array($res2);
		$query3 = 'SELECT sum(points_r), sum(fine) FROM orders WHERE date_end_remont<="'.$date_end_month.'" AND date_end_remont>="'.$date_start_month.'" AND bool_ready = "1" AND id_master = "'.$_SESSION['id'].'"';
		$res3=mysql_query($query3);
		$count_date=mysql_fetch_array($res3);
		$d = $count_date['0']+1-1;
		$t = $count_date['1']+1-1;
			
		$r=$d-$t;
		
			$money.= 
				'<tr>
					<td><b>'.$month.'</b></td>
					<td>'.$d.'</td>
					<td>'.$t.'</td>
					<td>'.$r.'</td>
				</tr><tr></tr>';
		$money .= '</tbody></table></div></div>';
		$ball_all = '<div class="row-fluid"><a href="/?action=ball_all" class="btn btn-danger right">Статистика за весь период</a></div>';
		$GLOBALS['content'] .= <<<TPL
				{$money}
				{$ball_all}
TPL;
	}
	
	function ball_all(){
	$GLOBALS['h1']='Статистика по зарплате мастера';
	$money = '<div class="row-fluid"><div class="span6"><table class="table table-bordered"><thead><tr><th>Месяц</th><th>Бонусов (руб.)</th><th>Штрафов (руб.)</th><th>Заработано (руб.)</th></tr></thead><tbody>';
		
	//це все може потім зникнути
	$year_const = 2011;
	$year = date('Y');
	$month = date('m');
	//for($i=(int)$month; $i>0; $i--){
	for($i=(int)$month; $i>0; $i--){
		$date_start_month = unix_date("1.".$i.".".$year);
		$date_end_month = unix_date("1.".($i+1).".".$year);
		$mon = array('нолябрь','январь','февраль','март','апрель','май','июнь','июль','август','сентябрь','октябрь','ноябрь','декабрь');
		$date = date('Y.m.d', $date_start_month);
		
		$query2 = "SELECT date_end_remont FROM orders";
		$res2=mysql_query($query2);
		$row2=mysql_fetch_array($res2);
		$query3 = 'SELECT sum(points_r), sum(fine) FROM orders WHERE date_end_remont<="'.$date_end_month.'" AND date_end_remont>="'.$date_start_month.'" AND bool_ready = "1" AND id_master = "'.$_SESSION['id'].'"';
		$res3=mysql_query($query3);
		$count_date=mysql_fetch_array($res3);
		$d = $count_date['0']+1-1;
		$t = $count_date['1']+1-1;
			
		$r=$d-$t;
		
			$money.= 
				'<tr>
					<td><b>'.$mon[$i].'</b></td>
					<td>'.$d.'</td>
					<td>'.$t.'</td>
					<td>'.$r.'</td>
				</tr><tr></tr>';
		
	}
		
	for($j=$year-1;$j>=$year_const;$j--){
		for($i=1; $i<=12; $i++){
			$date_start_month = unix_date("1.".$i.".".$j);
			$date_end_month = unix_date("31.".$i.".".$j);
			$mon = array('нолябрь','январь','февраль','март','апрель','май','июнь','июль','август','сентябрь','октябрь','ноябрь','декабрь');
			$date = date('Y.m.d', $date_start_month);
			
			$query2 = "SELECT date_end_remont FROM orders";
			$res2=mysql_query($query2);
			$row2=mysql_fetch_array($res2);
			$query3 = 'SELECT sum(points_r), sum(fine) FROM orders WHERE date_end_remont<="'.$date_end_month.'" AND date_end_remont>="'.$date_start_month.'" AND bool_ready = "1" AND id_master = "'.$_SESSION['id'].'"';
			$res3=mysql_query($query3);
			$count_date=mysql_fetch_array($res3);
			$d = $count_date['0']+1-1;
			$t = $count_date['1']+1-1;
			
			$r=$d-$t;
				$money.= 
					'<tr>
						<td><b>'.$mon[$i].' '.$j.' года</b></td>
						<td>'.$d.'</td>
						<td>'.$t.'</td>
						<td>'.$r.'</td>
					</tr><tr></tr>';
			
		}
		}
		$money .= '</tbody></table></div></div>';
		
		$GLOBALS['content'] .= <<<TPL
				{$money}
TPL;
	}
	
//ФУНКЦІЯ РЕДАКТИРОВАНИЯ ПОЛЯ "Нужна запчасть"
	function edit_job_do(){//ajax редактирование поля нужна запчасть
		//$query = 'SELECT job FROM orders WHERE id = "'.$_GET['id'].'"';
		//$res=mysql_query($query);
		//$row=mysql_fetch_array($res);
		
			$all_job = $_GET['newdop'];
			$strSQL = 'UPDATE orders SET job = "'.$all_job.'" WHERE id = "'.$_GET['id'].'"';
			mysql_query($strSQL);
			echo $_GET['newdop'];
		
		exit();
	}
	//END!!

	
	
	//ФУНКЦІЯ РЕДАКТИРОВАНИЯ ПОЛЯ "ЧТО С АПАРАТОМ"
	function edit_what_aparat_do(){//ajax редактирование поля что с апаратом
		$query = 'SELECT id_master FROM orders WHERE id = "'.$_GET['id'].'"';
		$res=mysql_query($query);
		$row=mysql_fetch_array($res);
		
		if($row['id_master'] == $_SESSION['id']){
			$all_bug = $_GET['newdop'];
			$strSQL = 'UPDATE orders SET what_aparat = "'.$all_bug.'" WHERE id = "'.$_GET['id'].'"';
			mysql_query($strSQL);
			echo $_GET['newdop'];
		}
		exit();
	}
	//END!!
	
	//ФУНКЦІЯ РЕДАКТИРОВАНИЯ ПОЛЯ "Дата окончания"
	function edit_date_end(){//ajax редактирование поля date_end
		$query = 'SELECT id_master FROM orders WHERE id = "'.$_GET['id'].'"';
		$res=mysql_query($query);
		$row=mysql_fetch_array($res);
		
		if($row['id_master'] == $_SESSION['id']){
			$new_date = $_GET['newdop'];
			$date1 = explode(".",$new_date);
			$new_date = $date1[2].".".$date1[1].".".$date1[0];
			$a = unix_date($new_date);
	
			$strSQL = 'UPDATE orders SET date_end_remont = "'.$a.'" WHERE id = "'.$_GET['id'].'"';
			mysql_query($strSQL);
			echo $_GET['newdop'];
		}
		exit();
	}
	//END!!


	function take_bool(){//взять заказ
		$date_admision_remont = time();
		$strSQL = 'UPDATE orders SET id_master = "'.$_SESSION['id'].'", date_admision_remont = "'.$date_admision_remont.'" WHERE id = "'.$_GET['id'].'"';
		mysql_query($strSQL);

		header("Location: /?action=list_orders", true, 303);
	}
	
	//ФУНКЦИЯ ВИВОДУ ФОРМИ "СДЕЛАЛ"
	function what_yes(){
		$back_but = '<a href="/?action=my_table" class="btn btn-danger btn-large">Назад</a>';
		$GLOBALS['h1']='Что сделано?';
		$GLOBALS['content'] = <<<HTML
		<form method="post" action="?action=what_do"> 
			<div class="row-fluid">
				<div class="span6">
					<textarea name="what_master" class="span12" style="height:150px;" ></textarea>
					<input type="hidden" name="id" value="{$_GET['id']}">
				</div>
			</div>
			<div class="row-fluid">
				<div style="text-align:right;" class="span6">
					<input type="submit" class="btn btn-large btn-info" value="Сохранить"/> {$back_but}
				</div>
			</div>
					
	</form>
		
HTML;
	}
	
	//ФУНКЦИЯ ВИВОДУ ФОРМИ "Не СДЕЛАЛ"
	function what_no(){
		$back_but = '<a href="/?action=my_table" class="btn btn-danger btn-large">Назад</a>';
		$GLOBALS['h1']='Почему не сделано?';
		$GLOBALS['content'] = <<<HTML
		<form method="post" action="?action=what_dont"> 
			<div class="row-fluid">
				<div class="span6">
					<textarea name="what_master" class="span12" style="height:150px;" ></textarea>
					<input type="hidden" name="id" value="{$_GET['id']}">
				</div>
			</div>
			<div class="row-fluid">
				<div style="text-align:right;" class="span6">
					<input type="submit" class="btn btn-large btn-info" value="Сохранить"/> {$back_but}
				</div>
			</div>
					
	</form>
		
HTML;
	}
	
	function what_do(){//додатково
		$what_master = $_POST['what_master'];
		$id = $_POST['id'];
		//це я дописав
		$date_end_remont = time();
		$query = "SELECT points_r FROM orders WHERE id = {$id}";
		$sql = mysql_query($query);
		$row = mysql_fetch_array($sql);
		
		$query2 = "SELECT points FROM user WHERE id = {$_SESSION['id']}";
		$sql2 = mysql_query($query2);
		$row2 = mysql_fetch_array($sql2);
	
		$b = $row2['points'] + $row['points_r'];
		
		$strSQL = 'UPDATE orders SET date_end_remont = "'.$date_end_remont.'", bool_ready = "1", what_master="'.$what_master.'" WHERE id = "'.$id.'"';
		$strSQL1 = 'UPDATE user SET points = "'.$b.'" WHERE id = "'.$_SESSION['id'].'"';
		mysql_query($strSQL);
		mysql_query($strSQL1);
		//EnD
		header("Location: /?action=my_table", true, 303);
	}
	
	function what_dont(){//додатково
		$what_master = $_POST['what_master'];
		$id = $_POST['id'];
		
		$query_master = 'UPDATE orders SET what_master="'.$what_master.'" WHERE id="'.$id.'"';
		$result = mysql_query($query_master) or die(mysql_error());
		//це я дописав
		$date_end_remont = time();
		$strSQL = 'UPDATE orders SET date_end_remont = "'.$date_end_remont.'", bool_ready = "2", what_master="'.$what_master.'" WHERE id = "'.$id.'"';
		mysql_query($strSQL);
		//EnD
		header("Location: /?action=my_table", true, 303);
	}
	//
	
	function do_bool(){//готово сделано
		
		header("Location: /?action=what_yes&id={$_GET['id']}", true, 303);
	}
	
	function dont_bool(){//готово не сделано
		header("Location: /?action=what_no&id={$_GET['id']}", true, 303);
	}
	

	
	function history(){//история
	//ball_rub();
		
		//$date = time();
		$year = date('Y');
		$month = date('m');
		$mon = array('нолябрь','январь','февраль','март','апрель','май','июнь','июль','август','сентябрь','октябрь','ноябрь','декабрь');
		$date_start_month = unix_date("1.".(int)$month.".".$year);
		$date_end_month = unix_date("31.".((int)$month).".".$year);
		
		$GLOBALS['h1'] = "Моя история за ".$mon[(int)$month];
		
		$query = "SELECT * FROM orders WHERE bool_ready!='0' AND date_end_remont>={$date_start_month} AND date_end_remont<={$date_end_month} AND id_master ={$_SESSION['id']} ORDER BY date_admision_remont DESC";
		$sql = mysql_query($query) or die(mysql_error());
		
		$GLOBALS['content'] .= '
		<div class="row-fluid"><a href="/?action=history_year" class="btn btn-info right">История за год</a></div>
		<div class="row-fluid">
			<table class="table table-bordered">
			<thead> 
				<tr style="text-align:center;">
					<th>Статус</th>
					<th>№ заказа</th>
					<th>№ в базе</th>
					<th>Сц</th>
					<th>Модель</th>
					<th>Стоимость</th>
					<th>Балы в рублях</th>
					<th>Что с аппаратом</th>
					<th>Дата приема</th>
					<th>Дата окончания</th>
					<th>Дата клиента</th>
					<th>Срочно</th>
					<th>Что сделал/не сделал</th>
					<th></th>
				</tr>
			</thead>
			<tbody>
		';
			
		while($row = mysql_fetch_array($sql)){
			$quickly = 'Нет';
			if($row['bool_quickly'] == 1) {$quickly = 'Да';}
			
			$date_adm = date('Y.m.d H:i', $row['date_admision_remont']);
			if ($row['date_admision_remont'] == 0) {$date_adm = '-';}
			
			$date_end = date('Y.m.d', $row['date_end_remont']);
			if ($row['date_end_remont'] == 0) {$date_end = '-';}
			
			$date_client = date('Y.m.d', $row['date_client']);	//
			if ($row['date_client'] == 0) {$date_client = '-';}	
			
			$userlink = get_user_link($row['who_gave']);
			if ($row['who_gave'] == 0) {$userlink = '-';}
			$userlink_man = get_user_link($row['id_menedger']);
			if ($row['id_menedger'] == 0) {$userlink_man = '-';}
			$userlink_mast = get_user_link($row['id_master']); 
			if ($row['id_master'] == 0) {$userlink_mast = '-';}
			
			$status = get_status_hist($row);
			
			$GLOBALS['content'] .= <<<TPL
			<tr>
				<td>{$status}</td>
				<td>{$row['numb_order']}<br />{$row['client_name']}</td>
				<td>{$row['numb_order_base']}</td>
				<td>{$row['service']}</td>
				<td>{$row['model']}</td>
				<td>{$row['price']}</td>
				<td>{$row['points_r']}</td>
				<td>{$row['what_aparat']}</td>
				<td>{$date_adm}</td>
				<td>{$date_end}</td>
				<td>{$date_client}</td>
				<td>{$quickly}</td>
				<td>{$row['what_master']}</td>
				<td>
					Менеджер: {$userlink_man}<br/>
					Мастер: {$userlink_mast}<br/>
					Выдал: {$userlink}
				</td>
			</tr>	
TPL;
		}

		$GLOBALS['content'] .= '</tbody></table></div>';
		
		make_order_table(0);
	}
	
	//history for year
	function history_year(){
		$GLOBALS['h1'] = "Моя история за год"; 
		$date = time();
		$query = "SELECT * FROM orders WHERE bool_ready!='0' AND ({$date}-date_end_remont<=31536000) AND id_master ={$_SESSION['id']} ORDER BY date_admision_remont DESC";
		$sql = mysql_query($query) or die(mysql_error());
	
		$GLOBALS['content'] .= '</tbody></table></div>';
		$GLOBALS['content'] .= '
		<div class="row-fluid">
		<table class="table table-bordered">
			<thead> 
				<tr style="text-align:center;">
					<th>Статус</th>
					<th>№ заказа</th>
					<th>№ в базе</th>
					<th>Сц</th>
					<th>Модель</th>
					<th>Стоимость</th>
					<th>Балы в рублях</th>
					<th>Что с аппаратом</th>
					<th>Дата приема</th>
					<th>Дата окончания</th>
					<th>Дата клиента</th>
					<th>Срочно</th>
					<th>Что сделал/не сделал</th>
					<th></th>
				</tr>
			</thead>
			<tbody>
		';

		while($row = mysql_fetch_array($sql)){
			$quickly = 'Нет';
			if($row['bool_quickly'] == 1) {$quickly = 'Да';}
			
			$date = date('Y.m.d H:i', $row['date_admision']);
			if ($row['date_admision'] == 0) {$date = '-';}
			
			$date_end = date('Y.m.d', $row['date_end_remont']);
			if ($row['date_end_remont'] == 0) {$date_end = '-';}
			
			$date_client = date('Y.m.d', $row['date_client']);	//
			if ($row['date_client'] == 0) {$date_client = '-';}	
			
			$userlink = get_user_link($row['who_gave']);
			if ($row['who_gave'] == 0) {$userlink = '-';}
			$userlink_man = get_user_link($row['id_menedger']);
			if ($row['id_menedger'] == 0) {$userlink_man = '-';}
			$userlink_mast = get_user_link($row['id_master']); 
			if ($row['id_master'] == 0) {$userlink_mast = '-';}
			
			
			$status = get_status_hist($row);
			
			$GLOBALS['content'] .= <<<TPL
			<tr>
				<td>{$status}</td>
				<td>{$row['numb_order']}<br />{$row['client_name']}</td>
				<td>{$row['numb_order_base']}</td>
				<td>{$row['service']}</td>
				<td>{$row['model']}</td>
				<td>{$row['price']}</td>
				<td>{$row['points_r']}</td>
				<td>{$row['what_aparat']}</td>
				<td>{$date}</td>
				<td>{$date_end}</td>
				<td>{$date_client}</td>
				<td>{$quickly}</td>
				<td>{$row['what_master']}</td>
				<td>
					Менеджер: {$userlink_man}<br/>
					Мастер: {$userlink_mast}<br/>
					Выдал: {$userlink}
				</td>
			</tr>	
TPL;
		}
		$GLOBALS['content'] .= '</tbody></table></div>';
	}
	//
	
	function edit_diagnosis_do(){//ajax редактирование поля диагностика
		$query = 'SELECT diagnostik, id_master, service FROM orders WHERE id = "'.$_GET['id'].'"';
		$res=mysql_query($query);
		$row=mysql_fetch_array($res);
		
		$all_bug = $_GET['newdop'];
		$strSQL = 'UPDATE orders SET diagnostik = "'.$all_bug.'" WHERE id = "'.$_GET['id'].'"';
		mysql_query($strSQL);
		
		echo $_GET['newdop'];
		exit();
	}
	
	function make_order_table($relay = '0') {
		if ($relay == 1) { // backlog
			$query = "SELECT * FROM make_orders WHERE master='{$GLOBALS['user_name']}' AND stat='0'";
		} else {
			$query = "SELECT * FROM make_orders WHERE master='{$GLOBALS['user_name']}' ORDER BY stat";
		}
		
		$sql = mysql_query($query) or die(mysql_error());
	
		$GLOBALS['content'] .= <<<MAKE_ORD
			
			<table class="table table-bordered" style="margin-top: 50px;">
				<thead> 
					<tr>
						<th style="text-align: left; padding-left: 25px;">Дата заказа</th>
						<th style="text-align: left; padding-left: 25px;">Деталь</th>
						<th style="width: 300px;">Статус</th>
						<th style="width: 200px;">Удалить</th>
					</tr>
				</thead>
				<tbody>
MAKE_ORD;

		while($row = mysql_fetch_array($sql)) {
			$detail = $row['text_order'];
			$status = $row['stat'];
			$id = $row['id'];
			$dater = date("d.m.y H:i:s", $row['date_order']);
			
				if ($status == 0) {	$status = 'Не пришла';}
				elseif ($status == 2) {	$status = 'Пришла';}
				elseif ($status == 1) {	$status = 'Не будет';}
			
			
			$GLOBALS['content'] .= <<<MAKE_ORD
						<tr>
							<td  style="text-align: left; padding-left: 25px; width: 150px;">{$dater}</td>
							<td  style="text-align: left; padding-left: 25px;">{$detail}</td>
							<td style="width: 300px;">{$status}</td>
							<td style="width: 200px;"><a href="/?action=del_order&id={$id}" style="margin-bottom: 5px;">Удалить [x]</a></td>
						</tr>
MAKE_ORD;
		}

	if ($relay == 1) { // backlog
		$GLOBALS['content'] .= <<<MAKE_ORD
				</tbody>
			</table>
			<form action="/?action=make_order" method="POST">
				<b>Введите деталь, которую хотите заказать<b><br/>
				<div  style="margin: 5px 0;">
					<div style="float: left;">
						<input style="width: 305px;" type="text" name="text_order"/>
					</div>
					<div style="float: left; margin-left: 10px;">
						<button class="btn btn-inverse pull-right" type="submit">Заказать</button>
					</div>
					<div style="clear: both;"></div>
				</div>
			</form>
MAKE_ORD;
		}
	}
	
	function del_order() {
		$query = "DELETE FROM make_orders WHERE id={$_REQUEST['id']}";
		$sql = mysql_query($query) or die(mysql_error());
		
		echo "<meta http-equiv=\"refresh\" content=\"0;url=" . $_SERVER['HTTP_REFERER'] . "\">";
	}	
	
	function make_order() {
		$text_order = $_REQUEST['text_order'];
		$master = $GLOBALS['user_name'];
		
		
		$query1 = "SELECT * FROM user WHERE login='{$master}'";
		//$query = ("SELECT service_center FROM user WHERE login='{$master}'");
		$service = mysql_query($query1);
		$service = mysql_fetch_array($service);
		$service = $service['service_center'];
		$date_order = time();
		
		$query = "INSERT INTO make_orders (master, service_center, text_order, date_order) VALUES('$master', '$service', '$text_order', '$date_order')";
		$sql = mysql_query($query) or die(mysql_error());
		
		
		echo "<meta http-equiv=\"refresh\" content=\"0;url=" . $_SERVER['HTTP_REFERER'] . "\">";
		//$GLOBALS['content'] .= "qwfqwdwefqwdaew";		
	}
	
	function my_table(){//мой стол
		$GLOBALS['h1'] = 'Мой стол';
		
		make_order_table(1);
		
		$query = "SELECT * FROM orders WHERE bool_ready='0' AND id_master ={$_SESSION['id']} AND refusal=''";
		$sql = mysql_query($query) or die(mysql_error());
		
		$GLOBALS['content'] .= <<<TPL
		<div class="row-fluid">
			<div style="float: right;">
				<a href="/?action=make_order" style="color: #888; text-decoration: none;">Мои&nbsp;запчасти</a>
			</div>
			<div style="clear: both;"></div>
		<script>

			$(document).ready(function(){
				var oTable = $('#dt_gal').dataTable({
					"sDom": "<'row'>t<'row'<'span4'l><'span4'i><'span4'p>>",
				"sPaginationType": "bootstrap",
					"aaSorting": [[9, "desc"]],
					"aoColumns": [
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"bSortable": false},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"bSortable": false},
						{"bSortable": false}
					]
				});
				$('.icon-edit.diagn_edit').live('click', function(){
					var ths = $(this).closest('.diagn_form');
					ths.empty().html('<textarea></textarea><a href="#" class="diagn_btn btn">Редактировать</a>');
					$('.diagn_btn').click(function(){
						jQuery.ajax({
							url: '/',
							type: 'GET',
							data: {
								'action': 'edit_diagnosis_do',
								'id': $(this).closest('tr').attr('rel'),
								'newdop': ths.find('textarea').val()
							},
							success: function(data){
								//alert(data);
								ths.closest('td').find('.diagn_info').html(data);
								ths.html('<i class="icon-edit diagn_edit" title="Редактировать"></i>');
							}              
						});
						return false;
					});
				});				
				
				$('.icon-edit.date_edit').live('click', function(){
					var ths = $(this).closest('.date_form');
					ths.empty().html('<input type="text" class="datepk"/><a href="#" class="date_btn btn">Ok</a>');
					$('.datepk').datepicker({
					format: 'yyyy.mm.dd'
				}).focus();
					$('.date_btn').click(function(){
						jQuery.ajax({
							url: '/',
							type: 'GET',
							data: {
								'action': 'edit_date_end',
								'id': $(this).closest('tr').attr('rel'),
								'newdop': ths.find('input').val()
							},
							success: function(data){
								ths.closest('td').find('.date_info').html(data);
								ths.html('<i class="icon-edit date_edit" title="Изменить"></i>');
							}              
						});
						return false;
					});
				});
				
				$('.icon-edit.aparat_edit').live('click', function(){
					var ths = $(this).closest('.aparat_form');
					ths.empty().html('<textarea></textarea><a href="#" class="aparat_btn btn">Изменить</a>');
					$('.aparat_btn').click(function(){
						jQuery.ajax({
							url: '/',
							type: 'GET',
							data: {
								'action': 'edit_what_aparat_do',
								'id': $(this).closest('tr').attr('rel'),
								'newdop': ths.find('textarea').val()
							},
							success: function(data){
								ths.closest('td').find('.aparat_info').html(data);
								ths.html('<i class="icon-edit aparat_edit" title="Изменить"></i>');
							}              
						});
						return false;
					});
				});
				
				$('.icon-edit.zap_edit').live('click', function(){
					var ths = $(this).closest('.zap_form');
					ths.empty().html('<textarea></textarea><a href="#" class="zap_btn btn">Редактировать</a>');
					$('.zap_btn').click(function(){
						jQuery.ajax({
							url: '/',
							type: 'GET',
							data: {
								'action': 'edit_job_do',
								'id': $(this).closest('tr').attr('rel'),
								'newdop': ths.find('textarea').val()
							},
							success: function(data){
								//alert(data);
								ths.closest('td').find('.zap_info').html(data);
								ths.html('<i class="icon-edit zap_edit" title="Редактировать"></i>');
							}              
						});
						return false;
					});
				});
			});
		</script>
		<table class="table table-bordered" id="dt_gal">
			<thead> 
				<tr>
					<th>Статус</th>
					<th>№ заказа</th>
					<th>№ в базе</th>
					<th>Сц</th>
					<th>Модель</th>
					<th>Заявленая неисправность</th>
					<th>Диагностика</th>
					<th>Стоимость</th>
					<th>Балы в рублях</th>
					<th>Что с аппаратом</th>
					<th>Нужна запчасть</th>
					<th>Дата приема</th>
					<th>Дата окончания</th>
					<th>Дата клиента</th>
					<th>Срочно</th>
					
					<th></th>
					<th></th>
				</tr>
			</thead>
			<tbody>
TPL;

		while($row = mysql_fetch_array($sql)){
			$quickly = 'Нет';
			if($row['bool_quickly'] == 1) {$quickly = 'Да';}
			
			$date = date('Y.m.d H:i', $row['date_admision']);
			if ($row['date_admision'] == 0) {$date = '-';}
			
			$date_end = date('Y.m.d', $row['date_end_remont']);
			if ($row['date_end_remont'] == 0) {$date_end = '-';}
			
			$date_client = date('Y.m.d', $row['date_client']);	//
			if ($row['date_client'] == 0) {$date_client = '-';}	
			
			$userlink = get_user_link($row['who_gave']);
			if ($row['who_gave'] == 0) {$userlink = '-';}
			$userlink_man = get_user_link($row['id_menedger']);
			if ($row['id_menedger'] == 0) {$userlink_man = '-';}
			$userlink_mast = get_user_link($row['id_master']); 
			if ($row['id_master'] == 0) {$userlink_mast = '-';}
			if($_SESSION['id']==$row['id_master']){
				$do_master = '<a href="/?action=do_bool&id='.$row['id'].'" class="btn btn-mini btn-success btn_act">Сделал</a>';
				$dont_master = '<a href="/?action=dont_bool&id='.$row['id'].'" class="btn btn-danger btn-mini btn_act">Не сделал</a>';
				$dod_master = '<a href="/?action=dod_but&id='.$row['id'].'" class="btn btn-inverse btn-mini btn_act">Дополнительно</a>';
			}
			$status = get_status($row);

			$GLOBALS['content'] .= <<<TPL
			<tr rel="{$row['id']}">
				<td>{$status}</td>
				<td>{$row['numb_order']}<br />{$row['client_name']}</td>
				<td>{$row['numb_order_base']}</td>
				<td>{$row['service']}</td>
				<td>{$row['model']}</td>
				<td>{$row['problem_client']}</td>
				<td style="text-align:left;"><div class="diagn_info">{$row['diagnostik']}</div><div class="diagn_form"><i class="icon-edit diagn_edit" title="Редактировать"></i></div></td>
				<td>{$row['price']}</td>
				<td>{$row['points_r']}</td>
				<td style="text-align:left;"><div class="aparat_info">{$row['what_aparat']}</div><div class="aparat_form"><i class="icon-edit aparat_edit" title="Изменить"></i></div></td>
				<td style="text-align:left;"><div class="zap_info">{$row['job']}</div><div class="zap_form"><i class="icon-edit zap_edit" title="Редактировать"></i></div></td>
				<td>{$date}</td>
				<td style="text-align:left;"><div class="date_info">{$date_end}</div><div class="date_form"><i class="icon-edit date_edit" title="изменить"></i></div></td>
				<td>{$date_client}</td>
				<td>{$quickly}</td>
				
				<td>
					Менеджер: {$userlink_man}<br/>
					Мастер: {$userlink_mast}<br/>
					Выдал: {$userlink}
				</td>
				<td>
					<div>
						{$do_master}
						{$dont_master}
						{$dod_master}
					</div>
				</td>
			</tr>
TPL;
		}
		$GLOBALS['content'] .= '</table>';
		
		
	}
	
	function list_orders(){//все заказы (Очередь на ремонт)
		if(isset($_GET['filter'])){
			switch ($_GET['filter']){
			case 'all':
				$GLOBALS['h1'] = "Очередь на ремонт";
				$filter = "";
				break;
			case 'hot':
				$GLOBALS['h1'] = "Очередь на ремонт: срочные заказы";
				$filter = "AND bool_quickly=1";
				break;		
			case 'old':
				$GLOBALS['h1'] = "Очередь на ремонт: долго лежащие заказы";
				$filter = "AND date_admision<100000";
				break;
			case 'search':
				if(isset ($_GET['query'])){
					$GLOBALS['h1'] = 'Поиск "'.$_GET['query'].'" по вашим заказам';
					$query = $_GET['query'];
					$query = trim($query);
					$query = stripslashes($query); 
					$query = htmlspecialchars($query);
					$filter = "AND (numb_order_base LIKE '%{$query}%' OR numb_order LIKE '%{$query}%' OR model LIKE '%{$query}%' OR client_name LIKE '%{$query}%' OR mobile LIKE '%{$query}%')";//Странная ошибка когда буквы
				}
				break;
			default: 
				$GLOBALS['h1'] = "Очередь на ремонт";
				$filter = "";
				break;
			}
		}else{
			$GLOBALS['h1'] = "Очередь на ремонт";
			$filter = "";
		}
		
		if(isset($_GET['filter']) && $_GET['filter'] == 'search'){
			$query = "SELECT * FROM orders WHERE bool_work=1 {$filter}";
		}else{
			$query = "SELECT * FROM orders WHERE id_master='0' AND date_giving='0' AND refusal='' AND bool_work=1 {$filter}";
		}

		$sql = mysql_query($query) or die(mysql_error());
		
		$GLOBALS['content'] .= <<<TPL
		<div class="row-fluid">
		<script>
			$(document).ready(function(){
				var oTable = $('#dt_gal').dataTable({
					"sDom": "<'row'>t<'row'<'span4'l><'span4'i><'span4'p>>",
					"sPaginationType": "bootstrap",
					"aaSorting": [[8, "desc"]],
					"aoColumns": [
						{"bSortable": false},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"bSortable": false},
						{"bSortable": false},
						{"bSortable": false},
						{"sType": "string"},
						{"bSortable": false},
						{"sType": "string"},
						{"sType": "string"},
						{"sType": "string"},
						{"bSortable": false},
						{"bSortable": false}
					]
				});
				$('.icon-edit.diagn_edit').live('click', function(){
					var ths = $(this).closest('.diagn_form');
					ths.empty().html('<textarea></textarea><a href="#" class="diagn_btn btn">Редактировать</a>');
					$('.diagn_btn').click(function(){
						jQuery.ajax({
							url: '/',
							type: 'GET',
							data: {
								'action': 'edit_diagnosis_do',
								'id': $(this).closest('tr').attr('rel'),
								'newdop': ths.find('textarea').val()
							},
							success: function(data){
								//alert(data);
								ths.closest('td').find('.diagn_info').html(data);
								ths.html('<i class="icon-edit diagn_edit" title="Редактировать"></i>');
							}              
						});
						return false;
					});
				});
				
				$('.icon-edit.aparat_edit').live('click', function(){
					var ths = $(this).closest('.aparat_form');
					ths.empty().html('<textarea></textarea><a href="#" class="aparat_btn btn">Изменить</a>');
					$('.aparat_btn').click(function(){
						jQuery.ajax({
							url: '/',
							type: 'GET',
							data: {
								'action': 'edit_what_aparat_do',
								'id': $(this).closest('tr').attr('rel'),
								'newdop': ths.find('textarea').val()
							},
							success: function(data){
								ths.closest('td').find('.aparat_info').html(data);
								ths.html('<i class="icon-edit aparat_edit" title="Изменить"></i>');
							}              
						});
						return false;
					});
				});
				
				$('.icon-edit.zap_edit').live('click', function(){
					var ths = $(this).closest('.zap_form');
					ths.empty().html('<textarea></textarea><a href="#" class="zap_btn btn">Редактировать</a>');
					$('.zap_btn').click(function(){
						jQuery.ajax({
							url: '/',
							type: 'GET',
							data: {
								'action': 'edit_job_do',
								'id': $(this).closest('tr').attr('rel'),
								'newdop': ths.find('textarea').val()
							},
							success: function(data){
								//alert(data);
								ths.closest('td').find('.zap_info').html(data);
								ths.html('<i class="icon-edit zap_edit" title="Редактировать"></i>');
							}              
						});
						return false;
					});
				});
			});
		</script>
		<table class="table table-bordered" id="dt_gal">
			<thead> 
				<tr>
					<th>Статус</th>
					<th>№ заказа</th>
					<th>№ в базе</th>
					<th>Сц</th>
					<th>Модель</th>
					<th>Заявленая неисправность</th>
					<th>Диагностика</th>
					<th>Стоимость</th>
					<th>Балы в рублях</th>
					<th>Что с аппаратом</th>
					<th>Нужна запчасть</th>
					<th>Дата приема</th>
					<th></th>
					<th></th>
				</tr>
			</thead>
			<tbody>
TPL;

		while($row = mysql_fetch_array($sql)){
			$quickly = 'Нет';
			if($row['bool_quickly'] == 1) {$quickly = 'Да';}
			
			$date = date('Y.m.d H:i', $row['date_admision']);
			if ($row['date_admision'] == 0) {$date = '-';}
			
			$date_end = date('Y.m.d H:i', $row['date_end_remont']);
			if ($row['date_end_remont'] == 0) {$date_end = '-';}
			
			$date_client = date('Y.m.d H:i', $row['date_client']);	//
			if ($row['date_client'] == 0) {$date_client = '-';}		
			
			$userlink = get_user_link($row['who_gave']);
			if ($row['who_gave'] == 0) {$userlink = '-';}
			$userlink_man = get_user_link($row['id_menedger']);
			if ($row['id_menedger'] == 0) {$userlink_man = '-';}
			$userlink_mast = get_user_link($row['id_master']); 
			if ($row['id_master'] == 0) {$userlink_mast = '-';}

			$take_but = '';
			if ($row['id_master'] == 0){
				$take_but = '<a href="/?action=take_bool&id='.$row['id'].'" class="btn_act btn btn-mini">Взять</a>';
			}
			
			$do_but = '';
			if ($row['bool_ready']==0 && $row['id_master'] != 0 && $row['id_master']==$_SESSION['id']){
				$do_but = '<a href="/?action=do_bool&id='.$row['id'].'" class="btn_act btn btn-mini btn-success">Сделал</a>';
			}
			
			$dont_but = '';
			if ($row['bool_ready']==0 && $row['id_master'] != 0 && $row['id_master']==$_SESSION['id']){
				$dont_but = '<a href="/?action=dont_bool&id='.$row['id'].'" class="btn_act btn btn-danger btn-mini">Не сделал</a>';
			}
			
			$dod_but = '';
			if ($row['bool_ready']==0 && $row['id_master'] != 0 && $row['id_master']==$_SESSION['id']){
				$dod_but ='<a href="/?action=dod_but&id='.$row['id'].'" class="btn btn-inverse btn-mini btn_act">Дополнительно</a>';
			}
			$diag_my='<td>'.$row['diagnostik'].'</td>';
			$aparat_my='<td>'.$row['what_aparat'].'</td>';
			$job_my='<td>'.$row['job'].'</td>';
			if($_SESSION['id']==$row['id_master']){
				$diag_my='<td style="text-align:left;"><div class="diagn_info">'.$row['diagnostik'].'</div><div class="diagn_form"><i class="icon-edit diagn_edit" title="Редактировать"></i></div></td>';
				$aparat_my='<td style="text-align:left;"><div class="aparat_info">'.$row['what_aparat'].'</div><div class="aparat_form"><i class="icon-edit aparat_edit" title="Изменить"></i></div></td>';
				$job_my='<td style="text-align:left;"><div class="zap_info">'.$row['job'].'</div><div class="zap_form"><i class="icon-edit zap_edit" title="Редактировать"></i></div></td>';
			}
			
			
			
			$status = get_status_hist($row);
			
			$GLOBALS['content'] .= <<<TPL
			<tr rel="{$row['id']}">
				<td>{$status}</td>
				<td>{$row['numb_order']}<br />{$row['client_name']}</td>
				<td>{$row['numb_order_base']}</td>
				<td>{$row['service']}</td>
				<td>{$row['model']}</td>
				<td>{$row['problem_client']}</td>
				{$diag_my}
				<td>{$row['price']}</td>
				<td>{$row['points_r']}</td>
				{$aparat_my}
				{$job_my}
				<td>{$date}</td>
				<td>
					Менеджер: {$userlink_man}<br/>
					Мастер: {$userlink_mast}<br/>
					Выдал: {$userlink}
				</td>
				<td>
					<div>
						
						{$take_but}
						{$do_but}
						{$dont_but}
						{$dod_but}
					</div>
				</td>
			</tr>
TPL;
		}
		$GLOBALS['content'] .= '</tbody></table></div>';	
	}
	
	function dod_but_do(){//додатково
		$diagnostik = $_POST['diagnostik'];
		$id = $_POST['id'];
		$work = $_POST['what'];
		$date = $_POST['date_end_remont'];
		$date1 = explode(".",$date);
		$date = $date1[2].".".$date1[1].".".$date1[0];
	
		$a = unix_date($date);
	
		
		$query = 'UPDATE orders SET work="'.$work.'", diagnostik="'.$diagnostik.'", date_end_remont = "'.$a.'" WHERE id="'.$id.'"';
		
		$result = mysql_query($query) or die(mysql_error());
		header("Location: /?action=my_table", true, 303);
	}
	
	
	function dod_but(){//форма додатково
		$query = ("SELECT * FROM orders WHERE id='{$_GET['id']}'");
		$res=mysql_query($query);
		$row=mysql_fetch_array($res);
		
		$GLOBALS['h1'] = 'Дополнительно - '.$row['numb_order'].' ('.$row['numb_order_base'].')';
		
		$userlink_man = get_user_link($row['id_menedger']);
			if($row['id_menedger'] == 0){$userlink_man = '-';}
		
		$flag = 'Нет';
		if ($row['bool_quickly'] == 1) {$flag = 'Да';}
		
		$date1 = date('Y.m.d', $row['date_admision']);
		$date2 = date('Y.m.d', $row['date_admision_remont']);
		$date3 = date('Y.m.d', $row['date_end_remont']);
		if ($row['date_end_remont'] == 0) {$date3='';}
		
		
		$GLOBALS['content'] = <<<HTML
		<script>
			$(document).ready(function(){
				$('#dp1').datepicker({
					format: 'yyyy.mm.dd'
				});
			});
		</script>
		<form method="post" action="?action=dod_but_do"> 
			<div class="row-fluid">
				<div class="span6">
					<label>Дата приёма</label>
					<input type="text" disabled="disabled" value="{$date1}" class="span12">
				</div>
				<div class="span6">
					<label>Менеджер:</label>
					{$userlink_man}
				</div>
			</div>
			
			<div class="row-fluid">
				<div class="span6">
					<label>Дата согласия</label>
					<input type="text" disabled="disabled" value="{$date1}" class="span12">
				</div>
				<div class="span6">
					<label>Дата приёма на ремонт</label>
					<input type="text" disabled="disabled" value="{$date2}" class="span12">
				</div>
			</div>
			
			<div class="row-fluid">
				<div class="span6">
					<label>Дата окончания ремонта</label>
					<input type="text" name = "date_end_remont" id="dp1" value="{$date3}" class="span12"/>
				</div>
				<div class="span6">
					<label>Балы</label>
					<input type="text" disabled="disabled" value="{$row['points']}" class="span12">
				</div>
			</div>	
			<div class="row-fluid">
				<div class="span6">
					<label>Балы в рублях</label>
					<input type="text" disabled="disabled" name = "points_r" value="{$row['points_r']}" class="span12">
				</div>
			</div>
			
			<div class="row-fluid">
				<div class="span6">
					<label>Диагностика</label>
					<textarea name = "diagnostik" disabled="disabled" style="height:90px;" class="span12">{$row['diagnostik']}</textarea>
				</div>
				<div class="span6">
					<label>ФИО</label>
					<input type="text" disabled="disabled" name="fio" value="{$row['client_name']}" class="span12">
					<label>Контактный телефон</label>
					<input type="text" disabled="disabled" name="tel" value="{$row['mobile']}" class="span12">
				</div>
			</div>
			
			<div class="row-fluid">
				<div class="span6">
					<label>Стоимость</label>
					<textarea name = "price" disabled="disabled" style="height:90px;" class="span12">{$row['price']}</textarea>
				</div>
				<div class="span6">
					<label>IMEI</label>
					<input type="text" disabled="disabled" name="imei" value="{$row['imei']}" class="span12">
					<label>Срочно</label>
					<input type="text" class="span12" disabled="disabled" name="srochno" value="{$flag}">	
				</div>
			</div>
			
			<div class="row-fluid">
				<div class="span6">
					<label>Неисправность (со слов клиента)</label>
					<textarea   name = "problem" disabled="disabled" style="height:90px;" class="span12">{$row['problem_client']}</textarea>
				</div>
				<div class="span6">
					<label>Что сделал(мастер)</label>
					<textarea  name="what" disabled="disabled" style="height:90px;" class="span12">{$row['work']}</textarea>
				</div>
			</div>
			
			<div class="row-fluid">
				<div style="text-align:right;" class="span6">
					<input type="submit" class="btn btn-large btn-info" value="Сохранить">
					<input type="hidden" name="id" value="{$row['id']}">
				</div>
			</div>
					
	</form>
		
HTML;
			
	}
?>